package com.lucifer.cn.util;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.lucifer.cn.dao.UserDao;
import com.lucifer.cn.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lucifer
 * @version 1.0
 * @date 2020/6/27
 */
public class UserDataListener extends AnalysisEventListener<User> {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserDataListener.class);
    /**
     * 每隔 x 条存储数据库,实际使用中可以3000条,然后清理list,方便内存回收
     */
    private static final int BATCH_COUNT = 5;

    List<User> list = new ArrayList();

    private UserDao userDao = new UserDao();

    /**
     * 读取数据会执行 invoke 方法
     * @param user  读取的数据类型
     * @param analysisContext 分析上下文
     */
    @Override
    public void invoke(User user, AnalysisContext analysisContext) {
        LOGGER.info("解析到一条数据:{}",JSON.toJSONString(user));
        list.add(user);
        if (list.size() >= BATCH_COUNT){
            saveData();//持久化逻辑
            list.clear();
        }

    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        LOGGER.info("所有数据解析完成!");
    }

    private void saveData(){
        LOGGER.info("{}条数据,开始存储数据库!",list.size());
        userDao.save(list);
        LOGGER.info("存数据库成功!");
    }
}
